﻿using SqlSugar;
using Store.Manager.ERP.Common.Models;
using Store.Manager.ERP.Domain;
using Store.Manager.ERP.Domain.Entities;
using Store.Manager.ERP.Domain.Repositories;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Store.Manager.ERP.Application.Services
{
    public class InventoryService : IInventoryService
    {
        private readonly IInventoryRepository _inventoryRepository;
        private readonly IOrganizationRepository _organizationRepository;
        private readonly IProductRepository _productRepository;
        public InventoryService(IInventoryRepository inventoryRepository, IOrganizationRepository organizationRepository, IProductRepository productRepository)
        {
            _inventoryRepository = inventoryRepository;
            _organizationRepository = organizationRepository;
            _productRepository = productRepository;
        }

        public async Task<CommonResponse> InitializeInventoryAsync(string organizationCode, string productCode, int quantity)
        {
            _inventoryRepository.UnitOfWork.BeginTransaction(IsolationLevel.Serializable);
            try
            {
                // 检查组织和商品是否存在
                var organization = await _organizationRepository.GetByIdAsync(organizationCode);
                if (organization == null)
                    return CommonResponse.Error("组织不存在");

                var product = await _productRepository.GetByCodeAsync(productCode);
                if (product == null)
                    return CommonResponse.Error("商品不存在");
                // 检查是否已有库存记录
                var existingInventory = await _inventoryRepository.GetByOrganizationAndProductAsync(organizationCode, productCode);
                if (existingInventory != null)
                {
                    // 更新库存
                    existingInventory.Quantity = quantity;
                    await _inventoryRepository.UpdateAsync(existingInventory);
                }
                else
                {
                    // 新增库存
                    var inventory = new Inventory
                    {
                        OrganizationCode = organizationCode,
                        ProductCode = productCode,
                        Quantity = quantity
                    };
                    await _inventoryRepository.AddAsync(inventory);
                }
                _inventoryRepository.UnitOfWork.Commit();
                return CommonResponse.OK("初始化成功");
            }
            catch (Exception ex)
            {
                _inventoryRepository.UnitOfWork.Rollback();
                return CommonResponse.Error($"初始化库存时发生错误: {ex.Message}");
            }
        }
    }
}
